import { ref, shallowRef } from 'vue';
import useApi from './useApi';

function useApiLoadMore(api, config) {
  const initialPage = { pageNumber: 1, pageSize: 10 };
  const initialData = { list: [], total: 0 };

  const page = ref(initialPage);
  const data = shallowRef(initialData);
  const hasMore = ref(true);

  const req = useApi(api, {
    auto: true,
    ...config,
    defaultParams: { ...initialPage, ...config.defaultParams },
    onPass(formated, params) {
      page.value = { pageNumber: params.pageNumber + 1, pageSize: params.pageSize };
      data.value = {
        list: data.value.list.concat(formated.list),
        total: formated.total,
      };

      hasMore.value = data.value.list.length < data.value.total;
      config.onPass?.(formated, params);
    },
  });

  // 查询
  const search = (params) => {
    req.run({ ...params, pageNumber: 1 });
  };

  // 继续加载
  const loadMore = () => {
    if (!hasMore.value) return;
    req.run({ pageNumber: page.value.pageNumber });
  };

  const clear = () => {
    page.value = initialPage;
    data.value = initialData;
    hasMore.value = true;
  };

  const refresh = () => {
    clear();
    loadMore();
  };

  return {
    ...req,
    page,
    data,
    hasMore,
    search,
    loadMore,
    clear,
    refresh,
  };
}

export default useApiLoadMore;
